package com.xxq.semester.service.impl.exam;

import com.xxq.semester.entity.exam.Exams;
import com.xxq.semester.mapper.ExamsMapper;
import com.xxq.semester.service.exam.IExamsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.xxq.semester.entity.exam.StudentExam;
import com.xxq.semester.mapper.StudentExamMapper;
import com.xxq.semester.mapper.ClassStudentsMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author saki
 * @since 2025-07-13
 */
@Service
public class ExamsServiceImpl extends ServiceImpl<ExamsMapper, Exams> implements IExamsService {

    @Autowired
    private StudentExamMapper studentExamMapper;
    @Autowired
    private ClassStudentsMapper classStudentsMapper;

    @Override
    public Integer createExam(Integer teacherId, String title, String description, LocalDateTime startTime, LocalDateTime endTime, Long duration, Integer classId) {
        Exams exam = new Exams();
        exam.setTeacherId(teacherId);
        exam.setTitle(title);
        exam.setDescription(description);
        exam.setCreatedAt(java.time.LocalDateTime.now());
        exam.setStatus("DRAFT"); // 初始状态为草稿
        exam.setStartTime(startTime);
        exam.setEndTime(endTime);
        exam.setDuration(duration);
        exam.setClassId(classId);
        // 保存考试记录
        this.save(exam);
        // 返回生成的examId
        return exam.getExamId();
    }

    @Override
    public void publishExam(Integer examId, Integer classId){
        Exams exam = this.getById(examId);
        if (exam != null) {
            exam.setStatus("PUBLISHED");
            this.updateById(exam);
            List<Integer> studentIds = classStudentsMapper.selectStudentIdsByClassId(classId);
            for (Integer studentId : studentIds) {
                StudentExam se = new StudentExam();
                se.setStudentId(studentId);
                se.setExamId(examId);
                studentExamMapper.insert(se);
            }
        }
    }
}
